﻿@model RH.Web.ViewModels.UtilityModels.ListConfig
@using RH.Web.Utility;
@using RH.Common.Extensions;
@using RH.Common.DB;
@{
    bool _ShowEditLink = NullHandler.GetBoolean(Model.AdhokModel); //ViewBag.ShowEditLink == null ? false : NullHandler.GetBoolean(ViewBag.ShowEditLink);
    ///By default Add to Wishlist will be shown in the UI
    //bool _ShowAddToWishlist = true ;//ViewBag.ShowAddToWishlist == null  ? true : NullHandler.GetBoolean(ViewBag.ShowAddToWishlist);
    String _LinkTarget = String.Empty;
    if(_ShowEditLink)
    {        
        _LinkTarget = " target=\"_blank\"";
    }
    //System.Data.DataTable dt = ViewBag.DataSource as System.Data.DataTable;
    long totalRecord = Model.DataSource == null || Model.Pager == null ? 0 : Model.Pager.TotalRecord; //dt.Rows.Count : 0;//NullHandler.GetInt(ViewBag.TotalRecord);
    int[] ProductCompareList = (from P in SessionCache.ProductCompareList select P.ID).ToArray();
    String _CompanyKey = ViewData[AppConstants.ViewDataKeys.COMPANY_KEY] as String;
    bool _ShowMessage = ViewBag.ShowMessage != null ? false : true ;
    Dictionary<int, int> _Occurance = new Dictionary<int, int>();
    bool _CalculateOccurance = ViewData[AppConstants.ViewDataKeys.CALCULATE_OCCURANCE] == null ? false : true;
    //bool _HasWishListInResult = Model.DataSource == null ? false : Model.DataSource.Columns.Contains("WishList");
    List<int> _Favorites = ViewData[AppConstants.ViewDataKeys.SUB_MODEL] as List<int>;
    
}

@if (totalRecord > 0)
{
    int loopCounter = 0;
    <div>
    @foreach (System.Data.DataRow product in Model.DataSource.Rows)
    {
        int productID = NullHandler.GetInt(product["ID"]);
        bool InCompareList = ProductCompareList.Contains(productID);
        //String compareClass = InCompareList ? "product-compared-link-button" : "product-compare-link-button btn-primary";
        //String compareText = InCompareList ? "Compare (-)" : "Compare (+)";
        String thumbnail = NullHandler.GetString(product["Thumbnail"]);
        String rowClass = ((loopCounter % 2) == 0) ? "rh-list-even" : "rh-list-odd";
        loopCounter++;
        if (_CalculateOccurance)
        {
            int categoryID = NullHandler.GetInt(product["CategoryID"]);
            if (_Occurance.Keys.Contains(categoryID))
            {
                _Occurance[categoryID]++;
            }
            else
            {
                _Occurance.Add(categoryID, 1);
            }
        }
        @*<a href="/product/details/@productID/@product["ProductUrl"]">*@
        <div class="row @rowClass">
            <div class="col-md-2">
                <div>
                    @Html.ProductThumb(thumbnail, productID, NullHandler.GetString(product["Name"]))
                </div>
                <div class="rh-top-5px">
                    @*@if (compareClass == "product-compared-link-button") {*@
                    @if (InCompareList) {
                        <a class="btn btn-default btn-sm product-compared-link-button" href="javascript:void(0);" onclick="RemoveFromProductCompare(@productID, this);"><i class="glyphicon glyphicon-minus"></i> Compare</a>
                    } else {
                        <a class="btn btn-success btn-sm product-compare-link-button" href="javascript:void(0);" onclick="AddToProductCompare(@productID, this);"><i class="glyphicon glyphicon-plus"></i> Compare</a>
                    }
                </div>
            </div>
            <div class="col-md-10">
                <div>
                    @if (_CompanyKey.IsNullOrEmpty()) {
                        <a href="/product/details/@(productID)/@(product["ProductUrl"])" @_LinkTarget><h3>@product["Name"]</h3></a>
                    } else {
                        String name = String.Format("<h3>{0}</h3>", NullHandler.GetString(product["Name"]));
                        @Html.CompanyProductDetailsLink(_CompanyKey, productID, NullHandler.GetString(product["ProductUrl"]), name)
                    }
                    <div><a href="/@NullHandler.GetString(product["CompanyUrl"])">@product["Company"]</a></div>
                    <div>
                        <h4><span class="text-muted">Price:</span> @Html.GetPriceText(product["Price"])</h4>
                    </div>
                </div>
                <div class="details">@MvcHtmlString.Create(WebUtil.FormatText(product["Description"].ToString().GetWords(40)))</div>
                <div class="rh-button-container">
                    @if (_ShowEditLink) { 
                    <a class="btn btn-primary btn-sm" href="@Url.PrivateUrl(String.Format("Edit/{0}", productID), "Product")"><i class="glyphicon glyphicon-edit"></i> Edit</a>
                    }
                    <button class="btn btn-default btn-sm@{if(_Favorites.Contains(productID)){<text> disabled</text>}}" onclick="AddToFavorite(@productID, this);"><i class="glyphicon glyphicon-star"></i> Add To Favourite</button>
                    <button class="btn btn-default btn-sm" onclick="ShowSendToFriend(@productID, this);"><i class="glyphicon glyphicon-send"></i> Send to a Friend</button>
                    <button class="btn btn-default btn-sm"><i class="glyphicon glyphicon-share"></i> FB Share</button>                    
                </div>
            </div>      
            <div class="clearfix"></div>
        </div>
    } 
    </div>
    if (_CalculateOccurance) {
        int mostCommonValue = 0;
        int highestCount = 0;
        foreach(KeyValuePair<int, int> pair in _Occurance){
            if (pair.Value > highestCount)
            {
                mostCommonValue = pair.Key;
                highestCount = pair.Value;
            }
        }
        <input type="hidden" id="hdnCategoryID" value="@mostCommonValue" />
    }
    RH.Web.ViewModels.ModalViewModel sendToFriendModal = new RH.Web.ViewModels.ModalViewModel("sendToFriendDialog", "Send Property to a Friend", "SendToFriend()");
    sendToFriendModal.Body = "_SendToFriendModal";
    sendToFriendModal.SaveButton = "Send";
    sendToFriendModal.BodyModel = SessionCache.CurrentUser == null ? String.Empty : SessionCache.CurrentUser.UserName;

    RH.Web.ViewModels.ModalViewModel messageDialog = new RH.Web.ViewModels.ModalViewModel("pl_message", "Confirmation", String.Empty);    
     
    @Html.Partial("_Modal", sendToFriendModal)
    @Html.Partial("_SendToFriendJS", "sendToFriendDialog")
    @Html.Partial("_Modal", messageDialog)
    <script language="Javascript" type="text/javascript">

    //function ShowDialogMessage(Message) {
    //    var $msgDiv = $('#dvMsg');
    //    $msgDiv.show().html(Message);

    //    var $messageDiv = $('#divMessageBox');
    //    $messageDiv.show();
    //    setTimeout(function () { $messageDiv.hide(); }, 3000);
    //}

        function AddToFavorite(id, btn) {
            ShowLoadingAnimation(false);
            var url = '@Url.Action("AddToFavorite", "Ajax", new { area = AppConstants.Area.PUBLIC })';
            var dialog = $('#@messageDialog.ControlID');
            Ajax(url, 'ID=' + id, function (result) {
                HideLoadingAnimation();
                if (result > 0) {
                    SetModalBody(dialog, SuccessMessageBox('The property info added to your favorite list, you can review them from your dashboard.', ''));
                    $(btn).addClass('disabled');
                    setTimeout(function () { $(dialog).modal('hide'); }, 3000);
                }
                else if(result == -1) {
                    var loginUrl = '@Url.PublicUrl("logon", "account")?ReturnUrl=@Request.RawUrl.UrlEncode()&pf=' + id;
                    SetModalBody(dialog, WarningMessageBox('Please <a href="' + loginUrl + '">login</a> to add property info to your favorite list.', 'Login Required!'));
                }
                else 
                    SetModalBody(dialog, WarningMessageBox('Sorry! something went wrong, unable to add property information to your favorite list.', ''));
                $(dialog).modal({ show: true });
            });
        }
    </script>
} else {
    if (_ShowMessage)
    {
        @Html.InfoMessageBox("Sorry! No Property Found for your given search criteria.")
    }
}


